package com.sy.musicapp.ui.play

import android.os.Handler
import android.os.Looper
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberImagePainter
import coil.transform.CircleCropTransformation
import com.sy.musicapp.R
import com.sy.musicapp.Util
import com.sy.musicapp.model.Music
import com.sy.musicapp.model.MusicViewModel
import com.sy.musicapp.model.PlayMode
import com.sy.musicapp.ui.common.LyricView
import com.sy.musicapp.ui.common.fillMaxSize
import com.sy.musicapp.ui.common.noRippleClickable
import com.sy.musicapp.ui.theme.Global
import com.sy.musicapp.ui.theme.tintText
import java.text.SimpleDateFormat
import java.util.*

/**
 * 独立播放页
 * @author SY
 * @since 2022-02-07 20:35
 **/

@ExperimentalAnimationApi
@Composable
fun PlayScreen(musicModel: MusicViewModel) {
    val isPlay by musicModel.isPlay.collectAsState()
    val mode by musicModel.playMode.collectAsState()
    val music: Music by musicModel.currentMusic.collectAsState()
    var progress by remember { mutableStateOf(0) }
    var percent by remember { mutableStateOf(0.0f) }
    var toggle by remember { mutableStateOf(true) }
    val handler = remember { Handler(Looper.getMainLooper()) }
    val runnable = remember {
        object : Runnable {
            override fun run() {
                try {
                    progress = musicModel.getCurrentProgress()
                    val temp = (progress.toFloat() / music.duration.toFloat())
                    percent = if (temp.isNaN()) 0.0f else temp
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                handler.postDelayed(this, 500)
            }
        }
    }
    DisposableEffect(music) {
        handler.post(runnable)
        onDispose {
            handler.removeCallbacks(runnable)
        }
    }

    Column(
        horizontalAlignment = CenterHorizontally,
        verticalArrangement = Arrangement.SpaceAround,
        modifier = Modifier.fillMaxSize(1f)
    ) {
        Column(
            horizontalAlignment = CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(10.dp),
            modifier = Modifier.padding(15.dp, 5.dp)
        ) {
            Text(text = music.name, fontSize = 18.sp, textAlign = TextAlign.Center)
            Text(text = music.artist, style = tintText)
        }
        AnimatedContent(
            modifier = Modifier
                .fillMaxHeight(0.6f)
                .noRippleClickable { toggle = !toggle },
            targetState = toggle
        ) { targetState: Boolean ->
            if (targetState) {
                Image(
                    painter = rememberImagePainter(
                        data = music.picUrl,
                        builder = {
                            error(R.drawable.keli)
                            transformations(CircleCropTransformation())
                        }
                    ),
                    contentDescription = "album",
                    modifier = Modifier
                        .fillMaxWidth(0.8f)
                        .heightIn(min = 200.dp)
                )
            } else {
                LyricView(
                    modifier = Modifier.fillMaxSize(1f, 0.5f),
                    lyricsEntryList = music.lyric,
                    liveTime = progress,
                    itemOnClick = {
                        Util.showLog(it)
                        musicModel.jumpTotime(it.time)
                    }
                )
            }

        }
        Column(horizontalAlignment = CenterHorizontally) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center
            ) {
                Text(
                    text = SimpleDateFormat(
                        "mm:ss",
                        Locale.SIMPLIFIED_CHINESE
                    ).format(progress),
                    fontSize = 14.sp,
                    color = Global.colors.onPrimary
                )
                Slider(
                    modifier = Modifier
                        .fillMaxWidth(0.7f)
                        .padding(horizontal = 5.dp),
                    value = percent,
                    onValueChange = {
                        handler.removeCallbacks(runnable)
                        percent = it
                    },
                    onValueChangeFinished = {
                        val target = percent * music.duration
                        musicModel.jumpTotime(target.toInt())
                        handler.post(runnable)
                    }
                )
                Text(
                    text = SimpleDateFormat(
                        "mm:ss",
                        Locale.SIMPLIFIED_CHINESE
                    ).format(music.duration),
                    fontSize = 14.sp,
                    color = Global.colors.onPrimary
                )
            }
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                IconButton(onClick = {
                    musicModel.changeMode()
                }) {
                    Icon(
                        imageVector = when (mode) {
                            PlayMode.ALL_CYCLE -> Icons.Rounded.Repeat
                            PlayMode.SINGLE_CYCLE -> Icons.Rounded.RepeatOne
                            PlayMode.RANDOM_PLAY -> Icons.Rounded.Shuffle
                        },
                        contentDescription = null,
                        tint = Global.colors.onPrimary
                    )
                }

                Row {
                    IconButton(onClick = {
                        handler.removeCallbacks(runnable)
                        musicModel.completed(true)
                    }) {
                        Icon(
                            imageVector = Icons.Rounded.SkipPrevious,
                            contentDescription = "prev",
                            tint = Global.colors.onPrimary
                        )
                    }
                    IconButton(onClick = {
                        musicModel.playStateChange()
                    }) {
                        Icon(
                            imageVector = if (isPlay)
                                Icons.Rounded.Pause
                            else
                                Icons.Rounded.PlayArrow,
                            contentDescription = null,
                            tint = Global.colors.onPrimary
                        )
                    }
                    IconButton(onClick = {
                        handler.removeCallbacks(runnable)
                        musicModel.completed()
                    }) {
                        Icon(
                            imageVector = Icons.Rounded.SkipNext,
                            contentDescription = "next",
                            tint = Global.colors.onPrimary
                        )
                    }
                }

                IconButton(onClick = {
                    musicModel.musicListShowChange()
                }) {
                    Icon(
                        imageVector = Icons.Rounded.QueueMusic,
                        contentDescription = null,
                        tint = Global.colors.onPrimary
                    )
                }
            }
        }
    }
}